package com.kc.controller;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kc.bean.Article;
import com.kc.service.impl.ArticleServiceImpl;
import com.kc.util.ResponesBean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-10-22
 */
@RestController
@RequestMapping("/pet/article")
public class ArticleController {

    @Resource
    private ArticleServiceImpl articleService;

    @Resource
    private ResponesBean responesBean;

    @PostMapping("release")
    private ResponesBean release(@RequestBody String json, HttpServletRequest request) throws IOException {
//      开始处理数据
        ObjectMapper mapper = new ObjectMapper();
        JsonNode arr = new ObjectMapper().readTree(json).get("article");
        Article article = mapper.readValue(arr.toString(),Article.class);

        String lable = new ObjectMapper().readTree(json).get("lable").toString();
        lable = lable.substring(lable.indexOf("\"") + 1, lable.length() - 1);
        String[] lables = lable.split(",");

        String token = request.getHeader("AcessToken");

        responesBean = articleService.inster(article,lables,token);
        return responesBean;
    }

    /**
     * 文件上传接口
     * @param file
     * @param AimsId
     * @param EditorType
     * @
     */
    @PostMapping("Upload")
    public ResponesBean Upload(@RequestParam MultipartFile file, String AimsId, String EditorType){
        responesBean = articleService.editor(file,AimsId,EditorType);
        return responesBean;
    }

    @PostMapping("viewarticle")
    public ResponesBean viewarticle(String ArticleId){
        Map<String,Object> map = new HashMap<>();
        map = articleService.ViewArticle(ArticleId);
        responesBean.setAll(200,"success",map);
        return responesBean;
    }
}
